<template>
  <el-dialog
    v-model="visible"
    title="添加代理商"
    width="500px"
    @close="resetForm"
  >
    <el-form ref="userFormRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="用户名" prop="userId">
        <el-select v-model="form.userId" filterable placeholder="请选择用户">
          <el-option
            v-for="item in userList"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确认</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { setAdminAgents } from "@/api/adminAgentApi";
import { message } from "@/utils/message";

interface UserForm {
  userId: string | number;
}
defineProps({
  userList: {
    type: Array as any,
    default: () => {}
  }
});
const visible = ref(false);

const form = reactive<UserForm>({
  userId: ""
});

const emits = defineEmits(["refresh"]);

const rules: FormRules = {
  userId: [{ required: true, message: "请选择用户", trigger: "change" }]
};

const userFormRef = ref<FormInstance>();

const submitForm = () => {
  userFormRef.value?.validate(async valid => {
    if (valid) {
      try {
        await setAdminAgents(form.userId);
        message("添加成功", { type: "success" });
        visible.value = false;
        emits("refresh");
      } catch (error) {
        console.error(error);
      }
    }
  });
};

const resetForm = () => {
  userFormRef.value?.clearValidate();
  userFormRef.value?.resetFields();
};

const open = () => {
  visible.value = true;
};

defineExpose({ open });
</script>
